package userPages;


import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import database.DBUtils;

/**
 * Servlet implementation class GetInstrumentData
 */
public class GetInstrumentData extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetInstrumentData() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//System.out.println("Hello from servlet2!");
		String instrType = request.getParameter("id");
		response.setContentType("text/xml");
		
		
		Connection conn = null;
		PreparedStatement selectUserStmt = null;
		ResultSet rs = null;
		try {
			conn = DBUtils.getConnection();
				selectUserStmt = conn
					.prepareStatement("SELECT i.id, i.name as name, it. name as type, i.description, i.messageforusers"
							+ " from instruments as i, instrumenttypes as it "
							+ "WHERE i.typeID = it.id && i.id =?;");
			selectUserStmt.setString(1, instrType);
			rs = selectUserStmt.executeQuery();
			if (rs == null || !rs.next()) {
				
				response.sendError(403);

			} else {
				String desc = rs.getString("description");
				if(desc.isEmpty())
					desc = "none";
				String mess = rs.getString("messageforusers");
				if(mess.isEmpty())
					mess = "none";
				
				response.getWriter().println("<start>" +
						"<name>"+rs.getString("name")+"</name>" +
						"<type>"+rs.getString("type")+"</type>" +
						"<desc>"+desc +"</desc>" +
						"<mess>"+mess+"</mess>" +
						"</start>");
								
				

			}
		} catch (Exception e) {
			
			response.sendError(403);
		} finally {
			DBUtils.close(rs);
			DBUtils.close(selectUserStmt);
			DBUtils.close(conn);
		}

		response.getWriter().flush();
		response.getWriter().close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
